package com.detroitchowfree.tasks;

import java.lang.reflect.Type;
import java.util.ArrayList;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import com.detroitchowfree.Article;
import com.detroitchowfree.IFetchArticlesObserver;
import com.detroitchowfree.LogUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


import android.os.AsyncTask;

public class FetchArticlesTask extends AsyncTask<String, Void, ArrayList<Article>> {
	private final String GET_ARTICLES_URL="http://detroitchow.com/getArticles.php?v=1&storeid=";
  private ArrayList<IFetchArticlesObserver> observers;
	public void registerObserver(IFetchArticlesObserver observer) {
		if(observers == null)
			observers = new ArrayList<IFetchArticlesObserver>();
		observers.add(observer);
	}
	
	private void onFetchComplete(ArrayList<Article> articles) {
		if(observers != null) {
			for(IFetchArticlesObserver observer : observers) {
				observer.onFetchArticles(articles);
			}
		}
	}
	
	@Override
  protected void onPostExecute(ArrayList<Article> articles) {
    // TODO Auto-generated method stub
    super.onPostExecute(articles);
    onFetchComplete(articles);
  }
	
	@Override
  protected ArrayList<Article> doInBackground(String... params) {
		ArrayList<Article> result=null;
    String requestContent;
    HttpClient httpclient = new DefaultHttpClient();
    String requestUrl = GET_ARTICLES_URL + params[0];
   // LogUtil.log("FetchArticleTask doInBackground", "requestUrl: " + requestUrl);
    HttpGet request = new HttpGet(requestUrl);
    ResponseHandler<String> handler = new BasicResponseHandler();
    Gson gson = new Gson();
    Type resultType = new TypeToken<ArrayList<Article>>(){}.getType();
    try {
      requestContent = httpclient.execute(request, handler);  
      result = gson.fromJson(requestContent, resultType);
     // LogUtil.log("FetchArticleTask doInBackground", "result: " + result.size());
       
    }catch(Exception e){
    	LogUtil.log("FetchArticlesTask doInBackground", e.getMessage());
    }
    httpclient.getConnectionManager().shutdown();
    
    return result;
  }

}
